package com.tyx.chargingpile.service;

import com.tyx.chargingpile.Enum.ServiceMessageEume;
import com.tyx.chargingpile.Enum.ServiceExceptionEume;
import com.tyx.chargingpile.cache.SocketChannelMap;
import com.tyx.chargingpile.service.exception.ServiceExcep;
import com.tyx.chargingpile.util.SpringBeanFactory;
import com.tyx.chargingpile.util.Util;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


@Service
public class MessageFactoryService {

    @Autowired
    SocketMessageService socketMessageService;

    /**
     * 根据报文统一处理进行发送
     * @param channelHandlerContext socket通道
     * @param context 收到报文内容
     */
    public void sendMsg(ChannelHandlerContext channelHandlerContext,byte[] context) throws Exception {
        Boolean isEffective = MessageService.isCheckBit(context);
        String msgStr = Util.BCD2String(context);
        if(!isEffective){
            throw new ServiceExcep(ServiceExceptionEume.MESSAGEISNOTCHECK,msgStr);
        }
        String commandId = MessageService.getCommandControl(context);
        if(StringUtils.isEmpty(commandId)){
            throw new ServiceExcep(ServiceExceptionEume.COMMANDIDISNULL,msgStr);
        }
        String pileNum = SocketChannelMap.getDeviceId(channelHandlerContext.channel().id().toString());
        // 心跳报文的日志太多，而且库里有保持，所以就不打印出来
        if (!commandId.equals("22")){
            LOGGER.info("客户端"+ channelHandlerContext.channel().id().toString() + ",接收到了："+ Util.BCD2String(context));
        }
//        LOGGER.info("客户端"+channelHandlerContext.channel().id()+",桩编号:" + pileNum +",指令控制编号："+commandId);
        String beanName = ServiceMessageEume.getEume(commandId).getBeanName();
        ChargingPileService chargingPileService = SpringBeanFactory.getBean(beanName,ChargingPileService.class);
        chargingPileService.execute(channelHandlerContext,context);
    }

    private final static Logger LOGGER = LoggerFactory.getLogger(MessageFactoryService.class);
}
